from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import threading
import json
import os
from ui.Ui_MainWindow import Ui_MainWindow

import Constant as C
import Function as F

from uipy.frm_set import Uipy_frm_set
from uipy.frm_about import Uipy_frm_About
from uipy.frm_news import Uipy_Frm_News

class Uipy_MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self,parent=None):
        super(Uipy_MainWindow, self).__init__(parent)

        self.frm_about = Uipy_frm_About()
        self.frm_set = Uipy_frm_set()
        self.frm_news = Uipy_Frm_News()

        self.setupUi(self)


        self.tW_PlugInList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tW_PlugInList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tW_PlugInList.customContextMenuRequested.connect(self.Menu)
        self.tW_PlugInList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tW_PlugInList.horizontalHeader().setStretchLastSection(True)
        self.tW_PlugInList.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.tW_PlugInList.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.tW_PlugInList.setColumnHidden(6,True)
        self.tW_PlugInList.currentItemChanged.connect(self.changeItem)
        self.show()

        self.pB_About.clicked.connect(self.showAbout)
        self.pB_Set.clicked.connect(self.showSet)
        self.pB_Refresh.clicked.connect(self.refreshPluginList)

        self.importPlugin()
        self.th_download = threading.Timer(0,self.setPBValue)
        self.th_download.start()
        if self.tW_PlugInList.rowCount() != -1:
            self.tW_PlugInList.selectRow(0)

        if C.showNewsFrm:
            self.frm_news.show()

    def changeItem(self):
        row = self.tW_PlugInList.currentRow()
        name = self.tW_PlugInList.item(row,0).text()
        if name != C.downloadDict['当前下载名称']:
            C.downloadDict['当前下载名称'] = name

    def setPBValue(self):
        name = C.downloadDict['当前下载名称']
        C.downloadDict[f'{name}下载'] = 0
        import time
        while True:
            name = C.downloadDict['当前下载名称']
            if name in C.downloadDict['名称']:
                self.progressBar.setValue(C.downloadDict[f'{name}下载'])
            else:
                self.progressBar.setValue(0)
            time.sleep(0.5)
            if C.Close:
                break

    def closeEvent(self, a0: QCloseEvent) -> None:
        del self.frm_about
        del self.frm_set
        C.Close = True

    def showAbout(self):
        self.frm_about.show()
    def showSet(self):
        self.frm_set.show()

    def Menu(self,pos):
        menu = QMenu()

        if self.tW_PlugInList.rowCount():
            row = self.tW_PlugInList.currentRow()
            name = self.tW_PlugInList.item(row,0).text()
            author = self.tW_PlugInList.item(row,1).text()
            version = self.tW_PlugInList.item(row,2).text()
            LICENSE = self.tW_PlugInList.item(row,4).text()
            remark = self.tW_PlugInList.item(row,5).text()

            itmRun = QAction(f'执行 {name}')
            itmDownload = QAction(f'下载 {name}')
            itmUpdate = QAction(f'更新 {name}')
            itmDelete = QAction(f'删除 {name}')

            if os.path.exists(f'Plugin/{name}/config.plc'):
                menu.addAction(itmRun)

                if F.isPluginWebVersionAfterLocal(name,version):
                    menu.addAction(itmUpdate)

                menu.addAction(itmDelete)

                if name in C.runLst:
                    itmRun.setEnabled(False)
                    itmDelete.setEnabled(False)
                else:
                    itmRun.setEnabled(True)
                    itmDelete.setEnabled(True)
            else:
                menu.addAction(itmDownload)

                if name in C.downloadDict['名称']:
                    itmDownload.setEnabled(False)
                else:
                    itmDownload.setEnabled(True)

            s = menu.addSeparator()
            itmRefresh = menu.addAction(f'刷新列表')
            s = menu.addSeparator()
            itmShowLicense = menu.addAction(f'显示 {name} 版权协议')
            itmAbout = menu.addAction(f'关于 {name}')

            action = menu.exec_(self.tW_PlugInList.mapToGlobal(pos))

            if action == itmRun:
                try:
                    C.runLst.append(name)
                    th = threading.Timer(0,F.runPlugin,(name,))
                    th.start()

                except Exception as e:
                    F.msgbox('提示',e)

            elif action == itmDownload:
                try:
                    C.downloadDict['名称'].append(name)

                    C.downloadDict['当前下载名称'] = name
                    C.downloadDict[f'{name}下载'] = 0

                    th = threading.Timer(0,F.downloadPlugin,(name,))
                    th.start()

                except Exception as e:
                    F.msgbox('提示',e)

            elif action == itmUpdate:
                try:
                    C.downloadDict['名称'].append(name)

                    th = threading.Timer(0,F.downloadPlugin,(name,))
                    th.start()

                except Exception as e:
                    F.msgbox('提示',e)

            elif action == itmDelete:
                r = F.deletePlugin(name)
                if not r['status']:
                    F.msgbox('提示',r['error'])
                else:
                    F.msgbox('提示','删除成功！')

            elif action == itmRefresh:
                self.importPlugin()

            elif action == itmAbout:
                F.msgbox(f'关于 {name}',f'{remark}')

            elif action == itmShowLicense:
                F.msgbox(f'关于 {name} 版权',f'{self.tW_PlugInList.item(row,4).text()}\n-------------------------------------\n{self.tW_PlugInList.item(row,6).text()}')
        self.refreshPluginList()

    def refreshPluginList(self):
        for row in range(self.tW_PlugInList.rowCount()):
            if not os.path.exists(f'Plugin/{self.tW_PlugInList.item(row,0).text()}/config.plc'):
                for col in range(self.tW_PlugInList.columnCount()):
                    self.tW_PlugInList.item(row, col).setBackground(Qt.gray)
            else:
                for col in range(self.tW_PlugInList.columnCount()):
                    self.tW_PlugInList.item(row, col).setBackground(Qt.white)

    def importPlugin(self):
        rdict = F.getWebPluginList()
        if rdict['status']:
            j = json.loads(rdict['data'])
            rowCount = len(j['插件'])
            self.tW_PlugInList.setRowCount(rowCount)

            for i in range(rowCount):
                self.tW_PlugInList.setItem(i,0,QTableWidgetItem(j['插件'][i]['名称']))
                self.tW_PlugInList.setItem(i,1,QTableWidgetItem(j['插件'][i]['作者']))
                self.tW_PlugInList.setItem(i,2,QTableWidgetItem(j['插件'][i]['版本']))
                self.tW_PlugInList.setItem(i,3,QTableWidgetItem(j['插件'][i]['最后更新时间']))
                for index in j['插件'][i]['版权协议']:
                    self.tW_PlugInList.setItem(i,4,QTableWidgetItem(index))
                    self.tW_PlugInList.setItem(i,6,QTableWidgetItem(j['插件'][i]['版权协议'][index]))
                self.tW_PlugInList.setItem(i,5,QTableWidgetItem(j['插件'][i]['说明']))

            self.refreshPluginList()

        else:
            F.msgbox('提示',f'{rdict["error"]}\n程序将退出!')
            exit(0)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        self.pB_Set.move(self.size().width()-32,0)
        self.pB_About.move(self.size().width()-64,0)
        self.pB_Refresh.move(self.size().width()-96,0)
        self.tW_PlugInList.resize(self.size().width(),self.size().height()-31)